<!DOCTYPE html>
<html>
<head>
<title>Count Shape Task</title>
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="../core/core.css">
<!-- JS -->
<script src="../core/core.js"></script>
<script src="../core/d3.v3.min.js"></script>
<script src="../common/shapes.js"></script>

<style>
#area { position: relative; height: 154px; width: 154px; }
#area_svg { width: 154px; height: 130px; }
#count-buttons { position: absolute; left: 6px; bottom: 2px; }
#count-buttons button { margin: 0 2px; }
button { width: 25px; }
</style>

<script>
shapes.SZ_Y = 6;
shapes.MAX_NUM_SHAPES = 10; // override variables from shapes.js (since counting is hard)

var createGrid = function(){
  // generate a new random grid of shapes
  d3.select('#count-buttons').html('');
  var grid = shapes.genGrid();
  var svg_elt = d3.select('#area_svg');
  shapes.renderGrid(svg_elt, grid); // instantiate the actual SVG shapes

  return grid;
}

var chooseShape = function(grid){
  // generate the problem instance
  if(core.randf(0,1) < 0.3) {
    var gtdesc = shapes.sampleDesc(); // answer could be 0
  } else {
    var gtix = core.randi(0, grid.shapes.length); // answer is 1+
    var gtdesc = shapes.generalDesc(grid.shapes[gtix]);
  }
  var gtshapes = grid.shapes.filter(function(x) { return shapes.shapeMatchesText(x, gtdesc); });

  return { gtdesc: gtdesc, gtshapes: gtshapes };
}

var bindClickEvents = function(grid, problemSet, query){
  var gtix = core.randi(0,5);
  var used = {};
  for(var query=0;query<5;query++) {
    if(gtix === query) {
      var c = problemSet.gtshapes.length; // true answer
    } else {
      while(true) {
        var c = core.randi(0,10);
        if(c !== problemSet.gtshapes.length && !used.hasOwnProperty(c)) { used[c] = 1; break; }
      }
    }
    // attach button and create a click handler
    var btn = d3.select('#count-buttons').append('button').html(c);
    var click_reward = gtix === query ? 1.0 : -1.0;
    btn.on('click', function(x) {
      return function(){ core.endEpisode(x, x > 0); d3.event.stopPropagation(); }
    }(click_reward)); // close over click_reward
  }

  // attach chandler to default click in random spot (penalize)
  grid.svg.on('click', function(){ core.endEpisode(-1); });
}

// create a problem instance
var genProblem = function() {
  var grid = createGrid();
  var problemSet = chooseShape(grid);
  var q = d3.select('#query').html('')

  q.append('div').html('How many ' + problemSet.gtdesc.text + 's are there?');
  var d = q.append('div');
  bindClickEvents(grid, problemSet, q);
}

window.onload = function() {
  core.startEpisode();
}
</script>
</head>
<body>
<div id="wrap">
  <div id="query"></div>
  <div id="area">
    <svg id="area_svg"></svg>
    <div id="count-buttons">
    </div>
  </div>
</div>
</body>
</html>
